package org.example.hansp.reflection.refleccreateinstance;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflecCreateInstance {
    @Test
    public void test() throws InstantiationException, IllegalAccessException {
        //1.通过无参构造器获取对象
        Class<Student> studentClass = Student.class;
        Student student = studentClass.newInstance();
        System.out.println(student);
    }
    @Test
    public void test2() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //通过共有的有参构造器获取对象
        Class<Student> studentClass = Student.class;
        Constructor<Student> constructor = studentClass.getConstructor(String.class);
        Student student = constructor.newInstance("lim");
        System.out.println(student);

    }
    @Test
    public void test3() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
       //通过私有的构造器获取对象
        Class<Student> studentClass = Student.class;
        Constructor<Student> declaredConstructor = studentClass.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);//爆破,使用反射可以访问私有
        Student student = declaredConstructor.newInstance("karly", 19);
        System.out.println(student);
    }
}

class Student{
    private String name="Kendou";
    private int age=3;

    public Student() {
    }
public Student(String name){
    this.name=name;
}

    private Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}